//
//  TourismHomeController.swift
//  AirTravel
//
//  Created by apple on 2021/7/23.
//

import UIKit
import JXBanner
import JXPageControl
import HandyJSON
import CoreLocation
import MapKit
class TourismHomeController: UIViewController {
    @IBOutlet weak var tabView: UITableView!
    @IBOutlet weak var topLine: NSLayoutConstraint!
    
    
    
    var cityData:[CityModel]?
    let identifyPC = "Pure1Cell"
    let identifyTh = "TourismHeadCell"
    let identifyHH = "HotelHeaderView"
    let identifyTD = "TourismDestinationCell"
    
    let locationManager = CLLocationManager()
    var currCity = ""
    
    var currCityIndex = ""
    
    lazy var banner: JXBanner = {
        let banner = JXBanner()
        banner.placeholderImgView.image = UIImage(named: "banner_placeholder")
        banner.delegate = self
        banner.tag = 0
        banner.dataSource = self
        banner.frame = CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: 203)
        return banner
    }()
    
    lazy var tourisModuleView: TourisModuleViewModel = {
        let iconView = TourisModuleViewModel()
        iconView.delegate = self
        return iconView
    }()
    
    lazy var tourisDestinationView: TourisDestinationViewModel = {
        let iconView = TourisDestinationViewModel()
        iconView.delegate = self
        return iconView
    }()

    lazy var hotelTagView: HotelTagViewModel = {
        let iconView = HotelTagViewModel()
        iconView.delegate = self
        return iconView
    }()
    
    lazy var tourismFlowView: TourismFlowViewModel = {
        let iconView = TourismFlowViewModel()
        iconView.delegate = self
        return iconView
    }()
    
    
    func locationStart() {
        //判断是否允许定位
        if CLLocationManager.locationServicesEnabled() {
            self.locationManager.delegate = self
            //设置定位精度
            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
            //每隔多少米定位一次（这里的设置为每隔百米)
            self.locationManager.distanceFilter = kCLLocationAccuracyHundredMeters
            self.locationManager.requestWhenInUseAuthorization()
            //开始定位
            self.locationManager.startUpdatingLocation()
        }else{
            YProgressHUD.showToast("定位服务当前可能尚未打开，请设置打开！")
        }
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true
    }
    
    
    func getCityData(){
        NetWorkRequest(API1.tgetCityCode) { responds in
            guard let model = JSONDeserializer<CityMainModel>.deserializeFrom(json: "\(responds)") else {
                return
                
            }
            
            self.cityData = model.data
            self.tabView.reloadData()
            
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if SCREEN_HEIGHT >= 812 {
            self.topLine.constant = 88
        }else{
            self.topLine.constant = 64
        }
        self.tabView.dataSource = self
        self.tabView.delegate = self
        self.tabView.tableFooterView = UIView.init()
        self.tabView.register(UINib.init(nibName: "TourismHeadCell", bundle: nil), forCellReuseIdentifier: identifyTh)
        self.tabView.register(UINib.init(nibName: "Pure1Cell", bundle: nil), forCellReuseIdentifier: identifyPC)
        self.tabView.register(UINib.init(nibName: "HotelHeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: identifyHH)
        self.tabView.register(UINib.init(nibName: "TourismDestinationCell", bundle: nil), forCellReuseIdentifier: identifyTD)
        if #available(iOS 11.0, *) {
            self.tabView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = true
        }
        
        getCityData()
        
//        self.tabView.reloadData()
    }

    @IBAction func backBtn(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
}

extension TourismHomeController:UITableViewDataSource,UITableViewDelegate{
    
    func numberOfSections(in tableView: UITableView) -> Int{
        return 2
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyTh) as! TourismHeadCell
            cell.selectionStyle = .none
            cell.topView.addSubview(self.banner)
            cell.inputTf.delegate = self
            return cell
        case 1:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyPC) as! Pure1Cell
            cell.selectionStyle = .none
//            if indexPath.section == 1 {
                self.tourisModuleView.bindViewToViewModel(collView: cell.collVIew)
//            }else{
//                self.tourismFlowView.bindViewToViewModel(collView: cell.collVIew)
//            }
            
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyTD) as! TourismDestinationCell
            cell.selectionStyle = .none
            self.tourisDestinationView.bindViewToViewModel(collView: cell.topColl)
            self.hotelTagView.bindViewToViewModel(collView: cell.bottomColl, number: 3)
            
            if let arr = self.cityData{
                self.hotelTagView.setUpTicketdata(arrat: arr)
            }
            
            
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        switch indexPath.section {
        case 0:
            return 240
        case 1:
            return ((SCREEN_WIDTH - 102) / 5 + 30) * 2 + 20
//        case 3:
//            return 276 * 5
        default:
            return (SCREEN_WIDTH - 50) / 3 + 35 + 120
        }
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        switch section {
        case 2:
            return 50
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{
        let headView = tableView.dequeueReusableHeaderFooterView(withIdentifier: identifyHH) as! HotelHeaderView
        switch section {
//        case 2:
//            headView.titleLab.text = "目的地推荐"
//            headView.img.isHidden = true
//            headView.moreBtn.isHidden = false
//            headView.leftLine.constant = 18
//            headView.moreBtn.tag = section
//            headView.moreBtn.addTarget(self, action: #selector(more(sender:)), for: .touchUpInside)
//        case 3:
//            headView.titleLab.text = "猜你喜欢"
//            headView.img.isHidden = true
//            headView.moreBtn.isHidden = false
//            headView.leftLine.constant = 18
        default:
            headView.img.isHidden = true
            headView.moreBtn.isHidden = true
            headView.titleLab.isHidden = true
        }
        return headView
    }
    
    @objc func more(sender:UIButton) {
        let vc = ClassificationTouristController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

extension TourismHomeController:JXBannerDataSource,JXBannerDelegate{
    
    func jxBanner(numberOfItems banner: JXBannerType) -> Int {
        return 3
    }
    
    func jxBanner(_ banner: JXBannerType) -> (JXBannerCellRegister) {
        return JXBannerCellRegister(type: nil,
                                    reuseIdentifier: "HomeBannerColl",
                                    nib: UINib(nibName: "HomeBannerColl", bundle: Bundle.main))
    }
    
    func jxBanner(_ banner: JXBannerType, cellForItemAt index: Int, cell: UICollectionViewCell) -> UICollectionViewCell {
        if let tempCell = cell as? HomeBannerColl {
//            if let array = self.banners {
//                let dic = array[index] as! Dictionary<String,Any>
//                tempCell.img.kf.setImage(with: URL.init(string: "\(dic["img"] ?? "")"))
//
//            }
            tempCell.img.image = UIImage.init(named: "图层5")
        }
        return cell
    }
    
    func jxBanner(_ banner: JXBannerType,
                  layoutParams: JXBannerLayoutParams)
        -> JXBannerLayoutParams {
        return layoutParams
            .itemSize(CGSize(width: SCREEN_WIDTH, height: 203))
    }
    
    func jxBanner(pageControl banner: JXBannerType, numberOfPages: Int, coverView: UIView, builder: JXBannerPageControlBuilder) -> JXBannerPageControlBuilder {
        let pageControl = JXPageControlScale()
        pageControl.contentMode = .bottomRight
        pageControl.activeSize = CGSize(width: 15, height: 6)
        pageControl.inactiveSize = CGSize(width: 6, height: 6)
        pageControl.activeColor = UIColor.white
        pageControl.inactiveColor = UIColor.white
        pageControl.columnSpacing = 0
        pageControl.isAnimation = true
        builder.pageControl = pageControl
        builder.layout = {
            pageControl.snp.makeConstraints { (maker) in
                maker.left.right.equalTo(coverView)
                maker.top.equalTo(coverView.snp.bottom).offset(-20)
                maker.height.equalTo(20)
            }
        }
        return builder
    }
    
    func jxBanner(_ banner: JXBannerType, params: JXBannerParams) -> JXBannerParams {
        return params.timeInterval(3)
    }
    
    func jxBanner(_ banner: JXBannerType,
                      didSelectItemAt index: Int) {
        
    }

}

extension TourismHomeController:TourisModuleDelegate{
    func tourisModuleClick(data: NSDictionary) {
        
    }
}

extension TourismHomeController:TourisDestinationDelegate{
    func tourisDestinationClick(data: NSDictionary) {
        
    }
}

extension TourismHomeController:HotelTagDelegate{
    func HotelTagClick(data: NSDictionary) {
        
    }
}

extension TourismHomeController:TourismFlowDelegate{
    func tourismFlowClick(data: NSDictionary) {
        
    }
    
    
}

extension TourismHomeController:UITextFieldDelegate{
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        let vc = TravelSearchCenterController()
        vc.currCityIndex = currCityIndex
        self.navigationController?.pushViewController(vc, animated: true)
        return false
    }
}


extension TourismHomeController:CLLocationManagerDelegate{
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
        self.locationManager.stopUpdatingLocation()
        //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
        let currentLocation = locations.last
        //获取当前所在的城市名
        let geocoder = CLGeocoder.init()
        if let current = currentLocation {
            //根据经纬度反向地理编译出地址信息
            geocoder.reverseGeocodeLocation(current) { array, error in
                if let locats = array {
                    if locats.count > 0 {
                        let placemark = locats[0]
                        //获取城市
                        self.currCity = placemark.locality ?? ""
                        if self.currCity.isEmpty == true{
                            //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                            self.currCity = placemark.administrativeArea ?? ""
                        }
     
                        
                    }
                }
            }
        }
        
        
    }
    
    
    func searchCityIndex(){
        for model in cityData!{
            if(model.city_name == currCity){
                currCityIndex = "\(model.city_id)"
            }
        }
    }
}
